package com.gujia.service;

import com.gujia.model.Comment;
import org.apache.commons.lang.CharUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeSet;

/**
 * Created by GuJia on 2017/6/29.
 */
@Service
public class SensitiveService implements InitializingBean {

    private static final Logger logger = LoggerFactory.getLogger(SensitiveService.class);

    /**
     * 默认敏感词替换符
     */
    private static final String DEFAULT_REPLACEMENT = "***";

    //读取敏文件
    @Override
    public void afterPropertiesSet() throws Exception {
        rootNode = new TrieNode();
        InputStream is = null;
        try {

            is = Thread.currentThread().getContextClassLoader().getResourceAsStream("SensitiveWord.txt");
            InputStreamReader read = new InputStreamReader(is);
            BufferedReader bufferedReader = new BufferedReader(read);
            String lineTxt;
            while ((lineTxt = bufferedReader.readLine()) != null) {
                lineTxt = lineTxt.trim();
                addWord(lineTxt);
            }

        }catch (Exception e){
            logger.error("Parse SensitiveWord failed! " + e.getMessage());
        }finally {
            is.close();
        }
    }

    //前缀树内部类
    private  class TrieNode{
        /**
         * true 关键词的终结；false 继续
         */
        private boolean end = false;
        /**
         * key下一个字符，value是对应的节点
         */
        private Map<Character,TrieNode> subNodes = new HashMap<Character, TrieNode>();

        /**
         * 向指定位置添加节点树
         * @param key
         * @param node
         */
        void addSubNode(Character key,TrieNode node){
            subNodes.put(key,node);
        }

        /**
         * 获取下个节点
         * @param key
         * @return
         */
        TrieNode getSubNode(Character key){
            return  subNodes.get(key);
        }

        boolean isKeyWordEnd(){
            return end;
        }

        void setKeyWordEnd(boolean end){
            this.end = end;
        }

        public int getSubNodeCount(){
            return subNodes.size();
        }


    }

    /**
     * 根节点
     */
    private TrieNode rootNode =new TrieNode();

    private void  addWord(String lineTxt){
        TrieNode tempNode = rootNode;

        for (int i=0;i< lineTxt.length();++i){
            Character c = lineTxt.charAt(i);

            TrieNode node = tempNode.getSubNode(c);

            if(node == null){
                node = new TrieNode();
                tempNode.addSubNode(c,node);
            }

            tempNode = node;

            if(i == lineTxt.length() -1){
                tempNode.setKeyWordEnd(true);
            }
        }

    }


    /**
     * 判断是否是一个符号
     */
    private boolean isSymbol(char c) {
        int ic = (int) c;
        // 0x2E80-0x9FFF 东亚文字范围
        return !CharUtils.isAsciiAlphanumeric(c) && (ic < 0x2E80 || ic > 0x9FFF);
    }


    /**
     * 过滤敏感词
     */
    public String filter(String text) {

        if (StringUtils.isBlank(text)) {
            return text;
        }
        String replacement = DEFAULT_REPLACEMENT;
        StringBuilder result = new StringBuilder();

        TrieNode tempNode = rootNode;
        int begin = 0; // 回滚数
        int position = 0; // 当前比较的位置

        while (position < text.length()) {
            char c = text.charAt(position);
            // 空格直接跳过
            if (isSymbol(c)) {
                if (tempNode == rootNode) {
                    result.append(c);
                    ++begin;
                }
                ++position;
                continue;
            }

            tempNode = tempNode.getSubNode(c);

            // 当前位置的匹配结束
            if (tempNode == null) {
                // 以begin开始的字符串不存在敏感词
                result.append(text.charAt(begin));
                // 跳到下一个字符开始测试
                position = begin + 1;
                begin = position;
                // 回到树初始节点
                tempNode = rootNode;
            } else if (tempNode.isKeyWordEnd()) {
                // 发现敏感词， 从begin到position的位置用replacement替换掉
                result.append(replacement);
                position = position + 1;
                begin = position;
                tempNode = rootNode;
            } else {
                ++position;
            }
        }

        result.append(text.substring(begin));

        return result.toString();
    }


    public static void main(String[] argv) {
        /*SensitiveService s = new SensitiveService();
        s.addWord("色情");
        s.addWord("色情狂");
        s.addWord("好色");
        System.out.print(s.filter("你好X色**情XX"));*/


        Comment t = new Comment();
        System.out.println(t.toString());
       // Map map2 = map;//引用地址
       // map2.put("0",1);

       // System.out.print(map.size());
        System.out.println(t.getUserId());
        put(t);


        System.out.println(t.getUserId());


    }

    public static void put(Comment test){

        Comment S = test;
        S.setUserId(1);
       // System.out.println(S.toString());
    }
}
